<template>
  <div class="senior-care-app">
    <!-- 主流程步骤 -->
    <div class="process-steps">
      <div
        v-for="(step, index) in mainSteps"
        :key="step.id"
        :class="[
          'step',
          { active: currentMainStep === index, completed: step.completed },
        ]"
        @click="goToMainStep(index)"
      >
        <div class="step-circle">{{ index + 1 }}</div>
        <div class="step-title">{{ step.title }}</div>
      </div>
    </div>

    <!-- 申请入住子流程步骤 -->
    <div v-if="currentMainStep === 0" class="sub-process-steps">
      <div
        v-for="(step, index) in applicationSubSteps"
        :key="step.id"
        :class="[
          'sub-step',
          {
            active: currentApplicationSubStep === index,
            completed: step.completed,
          },
        ]"
        @click="goToApplicationSubStep(index)"
      >
        <div class="sub-step-circle">{{ index + 1 }}</div>
        <div class="sub-step-title">{{ step.title }}</div>
      </div>
    </div>

    <!-- 入住评估子流程步骤 -->
    <div v-if="currentMainStep === 1" class="sub-process-steps">
      <div
        v-for="(step, index) in assessmentSubSteps"
        :key="step.id"
        :class="[
          'sub-step',
          {
            active: currentAssessmentSubStep === index,
            completed: step.completed,
          },
        ]"
        @click="goToAssessmentSubStep(index)"
      >
        <div class="sub-step-circle">{{ index + 1 }}</div>
        <div class="sub-step-title">{{ step.title }}</div>
      </div>
    </div>

    <!-- 流程内容区域 -->
    <div class="process-content">
      <!-- 申请入住流程内容 -->
      <template v-if="currentMainStep === 0">
        <!-- 基本信息 -->
        <div v-if="currentApplicationSubStep === 0" class="step-content">
          <h2>基本信息</h2>
          <el-form
            :model="applicationForm"
            label-width="120px"
            :rules="formRules"
            ref="basicInfoForm"
          >
            <el-form-item label="老人姓名" prop="name">
              <el-input
                v-model="applicationForm.name"
                placeholder="请输入"
                maxlength="10"
                show-word-limit
              />
            </el-form-item>

            <el-form-item label="老人身份证号" prop="idCard">
              <el-input
                v-model="applicationForm.idCard"
                placeholder="请输入"
                maxlength="18"
                show-word-limit
              />
            </el-form-item>

            <el-form-item label="性别" prop="gender">
              <el-radio-group v-model="applicationForm.gender">
                <el-radio label="男">男</el-radio>
                <el-radio label="女">女</el-radio>
              </el-radio-group>
            </el-form-item>

            <el-form-item label="出生日期" prop="birthDate">
              <el-date-picker
                v-model="applicationForm.birthDate"
                type="date"
                placeholder="选择日期"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>

            <el-form-item label="年龄">
              <el-input-number
                v-model="applicationForm.age"
                :min="0"
                :max="120"
              />
            </el-form-item>

            <el-form-item label="联系方式" prop="contact">
              <el-input
                v-model="applicationForm.contact"
                placeholder="请输入"
                maxlength="11"
                show-word-limit
              />
            </el-form-item>

            <el-form-item label="家庭住址" prop="address">
              <el-input
                v-model="applicationForm.address"
                type="textarea"
                placeholder="请输入"
                maxlength="100"
                show-word-limit
              />
            </el-form-item>

            <el-form-item label="民族" prop="ethnicity">
              <el-select
                v-model="applicationForm.ethnicity"
                placeholder="请选择"
              >
                <el-option
                  v-for="item in ethnicityOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>

            <el-form-item label="政治面貌" prop="politicalStatus">
              <el-select
                v-model="applicationForm.politicalStatus"
                placeholder="请选择"
              >
                <el-option
                  v-for="item in politicalStatusOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>

            <el-form-item label="宗教信仰" prop="religion">
              <el-select
                v-model="applicationForm.religion"
                placeholder="请选择"
              >
                <el-option
                  v-for="item in religionOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>

            <el-form-item label="婚姻状况" prop="maritalStatus">
              <el-select
                v-model="applicationForm.maritalStatus"
                placeholder="请选择"
              >
                <el-option
                  v-for="item in maritalStatusOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>

            <el-form-item label="文化程度" prop="education">
              <el-select
                v-model="applicationForm.education"
                placeholder="请选择"
              >
                <el-option
                  v-for="item in educationOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>

            <el-form-item label="经济来源" prop="incomeSource">
              <el-select
                v-model="applicationForm.incomeSource"
                placeholder="请选择"
              >
                <el-option
                  v-for="item in incomeSourceOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>

            <el-form-item label="特长爱好" prop="hobbies">
              <el-select
                v-model="applicationForm.hobbies"
                placeholder="请选择"
              >
                <el-option
                  v-for="item in hobbies"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>

            <el-form-item label="医疗保障" prop="medicalInsurance">
              <el-select
                v-model="applicationForm.medicalInsurance"
                placeholder="请选择"
              >
                <el-option
                  v-for="item in medicalInsuranceOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>

            <el-form-item label="医保卡号" prop="medicalCardNo">
              <el-input
                v-model="applicationForm.medicalCardNo"
                placeholder="请输入"
                maxlength="19"
                show-word-limit
              />
            </el-form-item>
          </el-form>
        </div>

        <!-- 家属信息 -->
        <div v-if="currentApplicationSubStep === 1" class="step-content">
          <h2>家属信息</h2>
          <div class="family-member-table">
            <el-table
              :data="familyMembers"
              style="width: 100%"
              empty-text="暂无家属信息，请添加"
            >
              <el-table-column prop="name" label="家属姓名" width="180">
                <template #default="scope">
                  <el-input
                    v-model="scope.row.name"
                    placeholder="请输入家属姓名"
                  />
                </template>
              </el-table-column>
              <el-table-column prop="contact" label="联系方式" width="200">
                <template #default="scope">
                  <el-input
                    v-model="scope.row.contact"
                    placeholder="请输入联系方式"
                    maxlength="11"
                  />
                </template>
              </el-table-column>
              <el-table-column
                prop="relationship"
                label="与老人关系"
                width="180"
              >
                <template #default="scope">
                  <el-select
                    v-model="scope.row.relationship"
                    placeholder="请选择关系"
                  >
                    <el-option
                      v-for="item in relationshipOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="120">
                <template #default="scope">
                  <el-button
                    type="danger"
                    size="small"
                    @click="removeFamilyMember(scope.$index)"
                    :disabled="familyMembers.length <= 1"
                  >
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>

            <div class="add-button-container">
              <el-button type="primary" @click="addFamilyMember" icon="Plus">
                添加家属
              </el-button>
            </div>

            <div class="family-tips">
              <el-alert
                title="提示"
                description="请至少填写一位家属信息，作为紧急联系人"
                type="info"
                :closable="false"
                show-icon
              />
            </div>
          </div>
        </div>

        <!-- 资料上传 -->
        <div v-if="currentApplicationSubStep === 2" class="step-content">
          <h2>资料上传</h2>
          <div class="upload-section">
            <!-- 一寸照片上传 -->
            <div class="upload-item">
              <div class="upload-label">一寸照片</div>
              <el-upload
                class="avatar-uploader"
                action="#"
                :show-file-list="false"
                :before-upload="beforeAvatarUpload"
                :http-request="handleAvatarUpload"
              >
                <img
                  v-if="applicationForm.photo"
                  :src="applicationForm.photo"
                  class="avatar"
                />
                <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
              </el-upload>
              <div class="upload-tips">
                请上传一寸免冠照片，支持JPG/PNG格式，大小不超过2MB
              </div>
            </div>

            <!-- 身份证人像面上传 -->
            <div class="upload-item">
              <div class="upload-label">身份证人像面</div>
              <el-upload
                class="avatar-uploader"
                action="#"
                :show-file-list="false"
                :before-upload="beforeIdCardUpload"
                :http-request="handleIdCardFrontUpload"
              >
                <img
                  v-if="applicationForm.idCardFront"
                  :src="applicationForm.idCardFront"
                  class="avatar"
                />
                <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
              </el-upload>
              <div class="upload-tips">
                请上传身份证人像面照片，支持JPG/PNG格式，大小不超过2MB
              </div>
            </div>

            <!-- 身份证国徽面上传 -->
            <div class="upload-item">
              <div class="upload-label">身份证国徽面</div>
              <el-upload
                class="avatar-uploader"
                action="#"
                :show-file-list="false"
                :before-upload="beforeIdCardUpload"
                :http-request="handleIdCardBackUpload"
              >
                <img
                  v-if="applicationForm.idCardBack"
                  :src="applicationForm.idCardBack"
                  class="avatar"
                />
                <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
              </el-upload>
              <div class="upload-tips">
                请上传身份证国徽面照片，支持JPG/PNG格式，大小不超过2MB
              </div>
            </div>
          </div>

          <div class="upload-preview" v-if="hasUploadedFiles">
            <h3>已上传文件预览</h3>
            <div class="preview-list">
              <div v-if="applicationForm.photo" class="preview-item">
                <span>一寸照片</span>
                <el-button
                  type="primary"
                  link
                  @click="previewImage(applicationForm.photo)"
                  >预览</el-button
                >
              </div>
              <div v-if="applicationForm.idCardFront" class="preview-item">
                <span>身份证人像面</span>
                <el-button
                  type="primary"
                  link
                  @click="previewImage(applicationForm.idCardFront)"
                  >预览</el-button
                >
              </div>
              <div v-if="applicationForm.idCardBack" class="preview-item">
                <span>身份证国徽面</span>
                <el-button
                  type="primary"
                  link
                  @click="previewImage(applicationForm.idCardBack)"
                  >预览</el-button
                >
              </div>
            </div>
          </div>
        </div>
      </template>

      <!-- 入住评估流程内容 -->
      <template v-else-if="currentMainStep === 1">
        <!-- 健康评估 -->
        <div v-if="currentAssessmentSubStep === 0" class="step-content">
          <h2>健康评估</h2>

          <!-- 疾病诊断 -->
          <div class="assessment-section">
            <h3>疾病诊断</h3>
            <el-checkbox-group
              v-model="healthAssessment.diseasesDiagnosis"
              @change="handleDiseaseChange"
            >
              <div class="checkbox-group">
                <el-checkbox
                  v-for="disease in diseaseOptions"
                  :key="disease.value"
                  :label="disease.value"
                  :disabled="getDiseaseDisabled(disease.value)"
                >
                  {{ disease.label }}
                </el-checkbox>
              </div>
            </el-checkbox-group>
          </div>

          <!-- 用药情况 -->
          <div class="assessment-section">
            <h3>用药情况</h3>
            <el-table
              :data="healthAssessment.medicationInfo"
              style="width: 100%"
              empty-text="暂无用药信息"
            >
              <el-table-column prop="name" label="药物名称" width="200">
                <template #default="scope">
                  <el-input
                    v-model="scope.row.name"
                    placeholder="请输入药物名称"
                    maxlength="20"
                    show-word-limit
                  />
                </template>
              </el-table-column>
              <el-table-column prop="method" label="服药方法" width="200">
                <template #default="scope">
                  <el-input
                    v-model="scope.row.method"
                    placeholder="请输入服药方法"
                  />
                </template>
              </el-table-column>
              <el-table-column prop="dosage" label="用药剂量" width="200">
                <template #default="scope">
                  <el-input
                    v-model="scope.row.dosage"
                    placeholder="请输入用药剂量"
                  />
                </template>
              </el-table-column>
              <el-table-column prop="frequency" label="用药频率" width="200">
                <template #default="scope">
                  <el-input
                    v-model="scope.row.frequency"
                    placeholder="请输入用药频率"
                  />
                </template>
              </el-table-column>
              <el-table-column label="操作" width="100">
                <template #default="scope">
                  <el-button
                    type="danger"
                    size="small"
                    @click="removeMedication(scope.$index)"
                    >删除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
            <div class="add-button-container">
              <el-button type="primary" @click="addMedication" icon="Plus">
                添加药物
              </el-button>
            </div>
          </div>

          <!-- 近30天内风险事件 -->
          <div class="assessment-section">
            <h3>近30天内风险事件</h3>
            <div class="risk-events">
              <div
                v-for="event in riskEvents"
                :key="event.key"
                class="risk-event-item"
              >
                <span class="event-label">{{ event.label }}：</span>
                <el-radio-group
                  v-model="healthAssessment.riskFactors[event.key]"
                >
                  <el-radio
                    v-for="option in riskOptions"
                    :key="option.value"
                    :label="option.value"
                  >
                    {{ option.label }}
                  </el-radio>
                </el-radio-group>
              </div>
            </div>
          </div>

          <!-- 身体健康情况 -->
          <div class="assessment-section">
            <h3>身体健康情况</h3>

            <!-- 伤口情况 -->
            <div class="health-subsection">
              <h4>伤口情况</h4>
              <el-checkbox-group
                v-model="healthAssessment.woundCondition"
                @change="handleWoundChange"
              >
                <div class="checkbox-group">
                  <el-checkbox
                    v-for="wound in woundOptions"
                    :key="wound.value"
                    :label="wound.value"
                    :disabled="getWoundDisabled(wound.value)"
                  >
                    {{ wound.label }}
                  </el-checkbox>
                </div>
              </el-checkbox-group>
            </div>

            <!-- 特殊医疗照护情况 -->
            <div class="health-subsection">
              <h4>特殊医疗照护情况</h4>
              <el-checkbox-group
                v-model="healthAssessment.specialMedicalCare"
                @change="handleSpecialCareChange"
              >
                <div class="checkbox-group">
                  <el-checkbox
                    v-for="care in specialCareOptions"
                    :key="care.value"
                    :label="care.value"
                    :disabled="getSpecialCareDisabled(care.value)"
                  >
                    {{ care.label }}
                  </el-checkbox>
                </div>
              </el-checkbox-group>
            </div>

            <!-- 自理能力 -->
            <div class="health-subsection">
              <h4>自理能力</h4>
              <el-radio-group v-model="healthAssessment.selfCareAbility">
                <el-radio
                  v-for="ability in selfCareOptions"
                  :key="ability.value"
                  :label="ability.value"
                >
                  {{ ability.label }}
                </el-radio>
              </el-radio-group>
            </div>

            <!-- 痴呆前兆 -->
            <div class="health-subsection">
              <h4>痴呆前兆</h4>
              <el-checkbox-group v-model="healthAssessment.dementiaPrecursors">
                <div class="checkbox-group">
                  <el-checkbox
                    v-for="sign in dementiaSignOptions"
                    :key="sign.value"
                    :label="sign.value"
                  >
                    {{ sign.label }}
                  </el-checkbox>
                </div>
              </el-checkbox-group>
            </div>
          </div>

          <!-- 其他 -->
          <div class="assessment-section">
            <h3>其他</h3>
            <el-input
              v-model="healthAssessment.otherConditions"
              type="textarea"
              placeholder="请输入其他需要说明的情况"
              :rows="3"
              maxlength="200"
              show-word-limit
            />
          </div>

          <!-- 体检报告 -->
          <div class="assessment-section">
            <h3>近期体检报告</h3>
            <el-upload
              class="upload-demo"
              action="#"
              :limit="1"
              :file-list="healthAssessment.medicalReport"
              :before-upload="beforeMedicalReportUpload"
              :http-request="handleMedicalReportUpload"
            >
              <el-button type="primary">上传文件</el-button>
              <template #tip>
                <div class="el-upload__tip">请上传pdf文件，大小在50MB以内</div>
              </template>
            </el-upload>
          </div>
        </div>

        <!-- 能力评估 -->
        <div v-if="currentAssessmentSubStep === 1" class="step-content">
          <h2>能力评估</h2>

          <div class="ability-assessment">
            <!-- 第一题 -->
            <div class="assessment-question">
              <h3>1. 自理能力评估</h3>
              <p>老人是否能够独立完成以下日常活动？</p>
              <el-radio-group
                v-model="abilityAssessment.selfCareAbility"
                @change="calculateScores"
              >
                <el-radio label="A"
                  >A. 完全自理（能独立完成所有日常活动）</el-radio
                >
                <el-radio label="B">B. 基本自理（需要少量帮助）</el-radio>
                <el-radio label="C">C. 部分自理（需要较多帮助）</el-radio>
                <el-radio label="D">D. 不能自理（完全依赖他人）</el-radio>
                <el-radio label="E">E. 无法评估</el-radio>
              </el-radio-group>
            </div>

            <!-- 第二题 -->
            <div class="assessment-question">
              <h3>2. 精神状态评估</h3>
              <p>老人的记忆力、定向力和判断力如何？</p>
              <el-radio-group
                v-model="abilityAssessment.mentalStatus"
                @change="calculateScores"
              >
                <el-radio label="A">A. 认知功能正常</el-radio>
                <el-radio label="B">B. 轻度认知障碍</el-radio>
                <el-radio label="C">C. 中度认知障碍</el-radio>
                <el-radio label="D">D. 重度认知障碍</el-radio>
                <el-radio label="E">E. 无法评估</el-radio>
              </el-radio-group>
            </div>

            <!-- 第三题 -->
            <div class="assessment-question">
              <h3>3. 感知觉与社会参与</h3>
              <p>老人的社交能力和情绪稳定性如何？</p>
              <el-radio-group
                v-model="abilityAssessment.perceptionSocialParticipation"
                @change="calculateScores"
              >
                <el-radio label="A">A. 社交活跃，情绪稳定</el-radio>
                <el-radio label="B">B. 社交一般，偶有情绪波动</el-radio>
                <el-radio label="C">C. 社交较少，情绪不稳定</el-radio>
                <el-radio label="D">D. 社交困难，情绪问题明显</el-radio>
                <el-radio label="E">E. 无法评估</el-radio>
              </el-radio-group>
            </div>

            <!-- 实时分数显示 -->
            <div class="score-preview">
              <h3>当前评估分数</h3>
              <el-card>
                <div class="score-display">
                  <div class="score-item">
                    <span>自理能力得分：</span>
                    <strong>{{ assessmentScores.selfCareScore }}分</strong>
                  </div>
                  <div class="score-item">
                    <span>精神状态得分：</span>
                    <strong>{{ assessmentScores.mentalStatusScore }}分</strong>
                  </div>
                  <div class="score-item">
                    <span>感知觉与社会参与得分：</span>
                    <strong>{{ assessmentScores.perceptionScore }}分</strong>
                  </div>
                  <div class="score-item total">
                    <span>评估总分：</span>
                    <strong>{{ assessmentScores.totalScore }}分</strong>
                  </div>
                  <div class="score-item level">
                    <span>能力初步等级：</span>
                    <el-tag
                      :type="getLevelType(assessmentScores.preliminaryLevel)"
                    >
                      {{ assessmentScores.preliminaryLevel }}
                    </el-tag>
                  </div>
                </div>
              </el-card>
            </div>
          </div>
        </div>

        <!-- 评估报告 -->
        <div v-if="currentAssessmentSubStep === 2" class="step-content">
          <h2>评估报告</h2>

          <div class="assessment-report">
            <!-- 能力评估结果 -->
            <div class="report-section">
              <h3 class="main-title">能力评估结果</h3>

              <!-- 各指标分数 -->
              <div class="subsection">
                <h4>各指标分数（分）</h4>
                <el-card class="score-card">
                  <div class="score-details">
                    <div class="score-row">
                      <span class="score-label">自理能力得分：</span>
                      <span class="score-value">{{ assessmentReport.selfCareScore }}分</span>
                    </div>
                    <div class="score-row">
                      <span class="score-label">精神状态得分：</span>
                      <span class="score-value">{{ assessmentReport.mentalStatusScore }}分</span>
                    </div>
                    <div class="score-row">
                      <span class="score-label">感知觉与社会参与得分：</span>
                      <span class="score-value">{{ assessmentReport.perceptionSocialScore }}分</span>
                    </div>
                  </div>
                </el-card>
              </div>

              <!-- 评估总分 -->
              <div class="subsection">
                <h4>评估总分（分）</h4>
                <el-card class="total-score-card">
                  <div class="total-score">
                    <span class="total-label">预估总分：</span>
                    <span class="total-value">{{ assessmentReport.estimatedTotalScore }}分</span>
                  </div>
                </el-card>
              </div>

              <!-- 能力初步等级 -->
              <div class="subsection">
                <h4>能力初步等级</h4>
                <el-card>
                  <div class="preliminary-level">
                    <el-tag :type="getLevelType(assessmentReport.preliminaryAbilityLevel)" size="large">
                      {{ assessmentReport.preliminaryAbilityLevel }}
                    </el-tag>
                  </div>
                </el-card>
              </div>
            </div>

            <!-- 护理等级结果 -->
            <div class="report-section">
              <h3 class="main-title">护理等级结果</h3>

              <!-- 能力等级变更依据 -->
              <div class="subsection">
                <h4>能力等级变更依据</h4>
                <el-card>
                  <div class="change-reasons">
                    <el-checkbox-group v-model="assessmentReport.levelChangeBasis">
                      <div class="reason-checkboxes">
                        <el-checkbox label="已诊断疾病超过3项">已诊断疾病超过3项</el-checkbox>
                        <el-checkbox label="风险事件超过3次">风险事件超过3次</el-checkbox>
                        <el-checkbox label="有特殊医疗照护需求">有特殊医疗照护需求</el-checkbox>
                        <el-checkbox label="有严重伤口情况">有严重伤口情况</el-checkbox>
                        <el-checkbox label="其他" @change="handleOtherBasisChange">其他</el-checkbox>
                      </div>
                    </el-checkbox-group>

                    <!-- 其他变更依据输入框 -->
                    <div v-if="assessmentReport.levelChangeBasis.includes('其他')" class="other-reason-input">
                      <el-input
                        v-model="assessmentReport.otherBasis"
                        type="textarea"
                        placeholder="请输入其他变更依据"
                        :rows="3"
                        maxlength="200"
                        show-word-limit
                      />
                    </div>
                  </div>
                </el-card>
              </div>

              <!-- 能力最终等级 -->
              <div class="subsection">
                <h4>能力最终等级</h4>
                <el-card>
                  <div class="final-level">
                    <el-radio-group v-model="assessmentReport.finalAbilityLevel">
                      <div class="level-options">
                        <el-radio label="能力完好">能力完好</el-radio>
                        <el-radio label="轻度失能">轻度失能</el-radio>
                        <el-radio label="中度失能">中度失能</el-radio>
                        <el-radio label="重度失能">重度失能</el-radio>
                      </div>
                    </el-radio-group>
                  </div>
                </el-card>
              </div>
            </div>

            <!-- 评估人员信息 -->
            <div class="report-section">
              <h3>评估人员信息</h3>
              <el-form :model="assessmentReport" label-width="120px">
                <el-form-item label="评估人员" prop="assessor">
                  <el-input
                    v-model="assessmentReport.assessor"
                    placeholder="请输入评估人员姓名"
                    maxlength="20"
                    show-word-limit
                  />
                </el-form-item>
                <el-form-item label="评估日期" prop="assessmentDate">
                  <el-date-picker
                    v-model="assessmentReport.assessmentDate"
                    type="date"
                    placeholder="选择评估日期"
                    value-format="YYYY-MM-DD"
                  />
                </el-form-item>
                <el-form-item label="总体评分">
                  <el-input-number
                    v-model="assessmentReport.overallScore"
                    :min="0"
                    :max="100"
                    :precision="1"
                    :step="0.5"
                  />
                  <span style="margin-left: 10px; color: #606266;">分</span>
                </el-form-item>
                <el-form-item label="护理等级">
                  <el-select v-model="assessmentReport.careLevel" placeholder="请选择护理等级">
                    <el-option label="特级护理" value="特级护理" />
                    <el-option label="一级护理" value="一级护理" />
                    <el-option label="二级护理" value="二级护理" />
                    <el-option label="三级护理" value="三级护理" />
                  </el-select>
                </el-form-item>
                <el-form-item label="评估备注">
                  <el-input
                    v-model="assessmentReport.remarks"
                    type="textarea"
                    placeholder="请输入评估备注信息"
                    :rows="3"
                    maxlength="500"
                    show-word-limit
                  />
                </el-form-item>
              </el-form>
            </div>

            <!-- 报告总结 -->
            <div class="report-section">
              <h3>报告总结</h3>
              <el-card>
                <div class="report-summary">
                  <div class="summary-item">
                    <strong>综合评估结果：</strong>
                    <span v-if="assessmentReport.finalAbilityLevel">
                      老人能力等级为 <el-tag :type="getLevelType(assessmentReport.finalAbilityLevel)" size="large">
                        {{ assessmentReport.finalAbilityLevel }}
                      </el-tag>，
                      建议护理等级为 <el-tag :type="getCareLevelType(assessmentReport.careLevel)" size="large">
                        {{ assessmentReport.careLevel }}
                      </el-tag>
                    </span>
                    <span v-else class="text-muted">请完成能力最终等级评定</span>
                  </div>
                  <div class="summary-item" v-if="assessmentReport.remarks">
                    <strong>评估说明：</strong>
                    <span>{{ assessmentReport.remarks }}</span>
                  </div>
                  <div class="summary-item">
                    <strong>评估人员：</strong>
                    <span>{{ assessmentReport.assessor || '待填写' }}</span>
                  </div>
                  <div class="summary-item">
                    <strong>评估日期：</strong>
                    <span>{{ assessmentReport.assessmentDate || '待选择' }}</span>
                  </div>
                </div>
              </el-card>
            </div>
          </div>
        </div>
      </template>

      <!-- 入住审批 -->
      <div v-if="currentMainStep === 2" class="step-content">
        <h2>入住审批</h2>
        <el-card class="approval-card">
          <div class="approval-process">
            <div class="process-item completed">
              <div class="process-icon">✓</div>
              <div class="process-info">
                <div class="process-title">发起申请-申请人住</div>
                <div class="process-time">2018-10-15 09:00:00</div>
                <div class="process-status">房迁（已发起）</div>
              </div>
            </div>
            <div class="process-item active">
              <div class="process-icon">!</div>
              <div class="process-info">
                <div class="process-title">（角色）处理-入住评估</div>
                <div class="process-time">2018-10-15 09:00:00</div>
                <div class="process-status">源明兰（已处理）</div>
              </div>
            </div>
            <div class="process-item pending">
              <div class="process-icon">?</div>
              <div class="process-info">
                <div class="process-title">审批结果</div>
                <div class="process-time">待处理</div>
                <div class="process-status">等待审批</div>
              </div>
            </div>
          </div>
        </el-card>

        <div class="approval-actions" style="margin-top: 20px">
          <el-button type="success" @click="approveApplication"
            >批准入住</el-button
          >
          <el-button type="danger" @click="rejectApplication"
            >拒绝申请</el-button
          >
        </div>
      </div>

      <!-- 入住配置 -->
      <div v-if="currentMainStep === 3" class="step-content">
        <h2>入住配置</h2>

        <!-- 入住设置 -->
        <div class="allocation-section">
          <h3 class="main-title">入住设置</h3>

          <!-- 入住期限 -->
          <div class="subsection">
            <h4>入住期限</h4>
            <el-card>
              <div class="date-range-picker">
                <el-form-item label="入住期限" label-width="100px">
                  <el-date-picker
                    v-model="allocationForm.stayPeriod"
                    type="daterange"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    value-format="YYYY-MM-DD"
                  />
                </el-form-item>
              </div>
            </el-card>
          </div>

          <!-- 护理等级 -->
          <div class="subsection">
            <h4>护理等级</h4>
            <el-card>
              <div class="care-level-select">
                <el-form-item label="护理等级" label-width="100px">
                  <el-select
                    v-model="allocationForm.careLevel"
                    placeholder="请选择护理等级"
                    style="width: 200px"
                  >
                    <el-option
                      v-for="level in careLevelOptions"
                      :key="level.value"
                      :label="level.label"
                      :value="level.value"
                    />
                  </el-select>
                </el-form-item>
              </div>
            </el-card>
          </div>

          <!-- 入住床位 -->
          <div class="subsection">
            <h4>入住床位</h4>
            <el-card>
              <div class="bed-selection">
                <el-form-item label="入住床位" label-width="100px">
                  <el-button
                    type="primary"
                    @click="openBedSelectionDialog"
                    icon="Search"
                  >
                    选择床位
                  </el-button>
                  <div
                    v-if="allocationForm.selectedBed"
                    class="selected-bed-info"
                  >
                    <span class="bed-info-text"
                      >已选择：{{ allocationForm.selectedBed }}</span
                    >
                  </div>
                </el-form-item>
              </div>
            </el-card>
          </div>
        </div>

        <!-- 费用设置 -->
        <div class="allocation-section">
          <h3 class="main-title">费用设置</h3>

          <!-- 费用期限 -->
          <div class="subsection">
            <h4>费用期限</h4>
            <el-card>
              <div class="fee-period">
                <el-form-item label="费用期限" label-width="100px">
                  <el-date-picker
                    v-model="allocationForm.feePeriod"
                    type="daterange"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    value-format="YYYY-MM-DD"
                  />
                </el-form-item>
              </div>
            </el-card>
          </div>

          <!-- 费用明细 -->
          <div class="subsection">
            <h4>费用明细</h4>
            <el-card>
              <div class="fee-details">
                <el-form :model="allocationForm" label-width="120px">
                  <!-- 押金 -->
                  <el-form-item label="押金">
                    <el-input-number
                      v-model="allocationForm.deposit"
                      :min="0"
                      :max="100000"
                      :precision="2"
                      :step="100"
                    />
                    <span class="fee-unit">元</span>
                  </el-form-item>

                  <!-- 护理费用 -->
                  <el-form-item label="护理费用">
                    <el-input-number
                      v-model="allocationForm.careFee"
                      :min="0"
                      :max="50000"
                      :precision="2"
                      :step="100"
                    />
                    <span class="fee-unit">元/月</span>
                  </el-form-item>

                  <!-- 床位费用 -->
                  <el-form-item label="床位费用">
                    <el-input-number
                      v-model="allocationForm.bedFee"
                      :min="0"
                      :max="30000"
                      :precision="2"
                      :step="100"
                    />
                    <span class="fee-unit">元/月</span>
                  </el-form-item>

                  <!-- 其他费用 -->
                  <el-form-item label="其他费用">
                    <el-input-number
                      v-model="allocationForm.otherFee"
                      :min="0"
                      :max="20000"
                      :precision="2"
                      :step="50"
                    />
                    <span class="fee-unit">元</span>
                  </el-form-item>

                  <!-- 医保支付 -->
                  <el-form-item label="医保支付">
                    <el-input-number
                      v-model="allocationForm.medicalInsurancePayment"
                      :min="0"
                      :max="10000"
                      :precision="2"
                      :step="50"
                    />
                    <span class="fee-unit">元</span>
                  </el-form-item>

                  <!-- 政府补贴 -->
                  <el-form-item label="政府补贴">
                    <el-input-number
                      v-model="allocationForm.governmentSubsidy"
                      :min="0"
                      :max="10000"
                      :precision="2"
                      :step="50"
                    />
                    <span class="fee-unit">元</span>
                  </el-form-item>

                  <!-- 费用总计 -->
                  <el-form-item label="费用总计" class="total-fee">
                    <span class="total-amount">
                      {{ calculateTotalFee }} 元
                    </span>
                  </el-form-item>
                </el-form>
              </div>
            </el-card>
          </div>
        </div>
      </div>

      <!-- 签约办理 -->
      <div v-if="currentMainStep === 4" class="step-content">
        <h2>签约办理</h2>
        <el-form :model="contractForm" label-width="120px">
          <el-form-item label="合同编号">
            <el-input v-model="contractForm.contractNumber" disabled />
          </el-form-item>

          <el-form-item label="合同名称">
            <el-input
              v-model="contractForm.contractName"
              placeholder="请输入"
              maxlength="20"
              show-word-limit
            />
          </el-form-item>

          <el-form-item label="合同期限">
            <el-date-picker
              v-model="contractForm.contractPeriod"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            />
          </el-form-item>

          <el-form-item label="签约日期">
            <el-date-picker
              v-model="contractForm.signDate"
              type="date"
              placeholder="选择签约日期"
            />
          </el-form-item>

          <el-form-item label="甲方姓名">
            <el-input
              v-model="contractForm.partyA"
              placeholder="请输入"
              maxlength="10"
              show-word-limit
            />
          </el-form-item>

          <el-form-item label="丙方联系方式">
            <el-input
              v-model="contractForm.partyCContact"
              placeholder="请输入"
              maxlength="11"
              show-word-limit
            />
          </el-form-item>

          <el-form-item label="上传合同">
            <el-upload
              action="#"
              :limit="1"
              :file-list="contractForm.contractFiles"
              :before-upload="beforeMedicalReportUpload"
              :http-request="handleMedicalReportUpload"
              accept=".pdf"
            >
              <el-button type="primary">上传文件</el-button>
              <template #tip>
                <div class="el-upload__tip">请上传pdf文件，大小在60M以内</div>
              </template>
            </el-upload>
          </el-form-item>
        </el-form>

        <div class="contract-preview" style="margin-top: 20px">
          <el-button type="primary" @click="previewContract"
            >预览合同</el-button
          >
          <el-button type="success" @click="completeContract"
            >完成签约</el-button
          >
        </div>
      </div>
    </div>

    <!-- 底部按钮 -->
    <div class="action-buttons">
      <!-- 申请入住子流程按钮 -->
      <template v-if="currentMainStep === 0">
        <el-button
          v-if="currentApplicationSubStep > 0"
          @click="prevApplicationSubStep"
          >上一步</el-button
        >
        <el-button
          v-if="currentApplicationSubStep < applicationSubSteps.length - 1"
          type="primary"
          @click="nextApplicationSubStep"
        >
          下一步
        </el-button>
        <el-button
          v-if="currentApplicationSubStep === applicationSubSteps.length - 1"
          type="success"
          @click="completeApplicationStep"
        >
          完成申请
        </el-button>
      </template>

      <!-- 入住评估子流程按钮 -->
      <template v-else-if="currentMainStep === 1">
        <el-button
          v-if="currentAssessmentSubStep > 0"
          @click="prevAssessmentSubStep"
          >上一步</el-button
        >
        <el-button
          v-if="currentAssessmentSubStep < assessmentSubSteps.length - 1"
          type="primary"
          @click="nextAssessmentSubStep"
        >
          下一步
        </el-button>
        <el-button
          v-if="currentAssessmentSubStep === assessmentSubSteps.length - 1"
          type="success"
          @click="completeAssessmentStep"
        >
          完成评估
        </el-button>
      </template>

      <!-- 主流程按钮 -->
      <template v-else>
        <el-button v-if="currentMainStep > 0" @click="prevMainStep"
          >返回</el-button
        >
        <el-button
          v-if="currentMainStep < mainSteps.length - 1"
          type="primary"
          @click="nextMainStep"
        >
          下一步
        </el-button>
        <el-button
          v-if="currentMainStep === mainSteps.length - 1"
          type="success"
          @click="submitCompleteApplication"
          :loading="submitting"
          :disabled="submitting"
        >
          {{ submitting ? "提交中..." : "提交" }}
        </el-button>
      </template>
    </div>

    <!-- 图片预览对话框 -->
    <el-dialog v-model="imagePreviewVisible" title="图片预览" width="50%">
      <img :src="previewImageUrl" style="width: 100%" alt="预览图片" />
    </el-dialog>

    <!-- 床位选择对话框 -->
    <el-dialog
      v-model="bedSelectionDialogVisible"
      title="选择床位"
      width="600px"
    >
      <div class="bed-selection-dialog">
        <div class="bed-list">
          <div
            v-for="bed in availableBeds"
            :key="bed.id"
            :class="['bed-item', { selected: selectedBedId === bed.id }]"
            @click="selectBed(bed)"
          >
            <div class="bed-info">
              <div class="bed-number">{{ bed.number }}</div>
              <div class="bed-details">
                <div>房间：{{ bed.room }}</div>
                <div>类型：{{ bed.type }}</div>
                <div>状态：{{ bed.status }}</div>
                <div class="bed-price">价格：{{ bed.price }}元/月</div>
              </div>
            </div>
          </div>
        </div>
        <div class="dialog-actions">
          <el-button @click="bedSelectionDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmBedSelection"
            >确定</el-button
          >
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, watch, onMounted } from "vue";
import { ElMessage, ElMessageBox, ElLoading } from "element-plus";
import { Plus } from "@element-plus/icons-vue";

// 主流程步骤
const mainSteps = ref([
  { id: 1, title: "申请入住", completed: false },
  { id: 2, title: "入住评估", completed: false },
  { id: 3, title: "入住审批", completed: false },
  { id: 4, title: "入住配置", completed: false },
  { id: 5, title: "签约办理", completed: false },
]);

// 申请入住子流程步骤
const applicationSubSteps = ref([
  { id: 1, title: "基本信息", completed: false },
  { id: 2, title: "家属信息", completed: false },
  { id: 3, title: "资料上传", completed: false },
]);

// 入住评估子流程步骤
const assessmentSubSteps = ref([
  { id: 1, title: "健康评估", completed: false },
  { id: 2, title: "能力评估", completed: false },
  { id: 3, title: "评估报告", completed: false },
]);

const currentMainStep = ref(0);
const currentApplicationSubStep = ref(0);
const currentAssessmentSubStep = ref(0);

// 申请入住表单
const applicationForm = reactive({
  name: "1111",
  idCard: "111111111111111111",
  gender: "男",
  birthDate: "2025-10-10",
  age: 50,
  contact: "15234621053",
  address: "1111111111",
  ethnicity: "1",
  politicalStatus: "1",
  religion: "1",
  maritalStatus: "1",
  education: "1",
  incomeSource: "1",
  hobbies: "1",
  medicalInsurance: "1",
  medicalCardNo: "11111",
  photo: "", // 一寸照片
  idCardFront: "", // 身份证正面照片
  idCardBack: "", // 身份证反面照片
});

// 家属信息
const familyMembers = ref([{ name: "11", contact: "11111111111", relationship: "配偶" }]);

// 健康评估数据
const healthAssessment = reactive({
  diseasesDiagnosis: [],
  medicationInfo: [{ name: "111", method: "111", dosage: "111", frequency: "111" }],
  riskFactors: {
    fall: "发生过1次",
    wandering: "发生过1次",
    choking: "发生过1次",
    suicide: "发生过1次",
    coma: "发生过1次",
  },
  woundCondition: [],
  specialMedicalCare: [],
  selfCareAbility: "",
  dementiaPrecursors: [],
  otherConditions: "",
  medicalReport: [],
});

// 能力评估数据
const abilityAssessment = reactive({
  selfCareAbility: "",
  mentalStatus: "",
  perceptionSocialParticipation: "",
});

// 评估分数计算
const assessmentScores = reactive({
  selfCareScore: 0,
  mentalStatusScore: 0,
  perceptionScore: 0,
  totalScore: 0,
  preliminaryLevel: "未评估",
});

// 评估报告数据 - 更新后的结构
const assessmentReport = reactive({
  // 评估分数
  selfCareScore: 0,
  mentalStatusScore: 0,
  perceptionSocialScore: 0,
  estimatedTotalScore: 0,
  preliminaryAbilityLevel: "未评估",
  
  // 等级变更依据
  levelChangeBasis: [],
  otherBasis: "",
  
  // 最终等级和评估信息
  finalAbilityLevel: "",
  assessmentDate: "",
  assessor: "",
  
  // 其他评估信息
  overallScore: 0,
  careLevel: "三级护理",
  remarks: "",
});

// 入住配置表单
const allocationForm = reactive({
  // 入住设置
  stayPeriod: [], // 入住期限
  careLevel: "", // 护理等级
  selectedBed: "", // 选择的床位

  // 费用设置
  feePeriod: [], // 费用期限
  deposit: 0, // 押金
  careFee: 0, // 护理费用
  bedFee: 0, // 床位费用
  otherFee: 0, // 其他费用
  medicalInsurancePayment: 0, // 医保支付
  governmentSubsidy: 0, // 政府补贴
});

// 护理等级选项
const careLevelOptions = [
  { label: "等级1", value: "等级1" },
  { label: "等级2", value: "等级2" },
  { label: "等级3", value: "等级3" },
  { label: "等级4", value: "等级4" },
  { label: "等级5", value: "等级5" },
  { label: "等级6", value: "等级6" },
  { label: "等级7", value: "等级7" },
  { label: "等级8", value: "等级8" },
  { label: "等级9", value: "等级9" },
  { label: "等级10", value: "等级10" },
];

// 可用床位数据
const availableBeds = ref([
  {
    id: 1,
    number: "A101-01",
    room: "A101",
    type: "单人间",
    status: "空闲",
    price: 2000,
  },
  {
    id: 2,
    number: "A101-02",
    room: "A101",
    type: "单人间",
    status: "空闲",
    price: 2000,
  },
  {
    id: 3,
    number: "B201-01",
    room: "B201",
    type: "双人间",
    status: "空闲",
    price: 1500,
  },
  {
    id: 4,
    number: "B201-02",
    room: "B201",
    type: "双人间",
    status: "已预定",
    price: 1500,
  },
  {
    id: 5,
    number: "C301-01",
    room: "C301",
    type: "多人间",
    status: "空闲",
    price: 1000,
  },
  {
    id: 6,
    number: "C301-02",
    room: "C301",
    type: "多人间",
    status: "空闲",
    price: 1000,
  },
  {
    id: 7,
    number: "C301-03",
    room: "C301",
    type: "多人间",
    status: "空闲",
    price: 1000,
  },
]);

// 床位选择相关
const bedSelectionDialogVisible = ref(false);
const selectedBedId = ref(null);

// 签约表单
const contractForm = reactive({
  contractNumber: "HT2048101015000001",
  contractName: "",
  contractPeriod: [],
  signDate: "",
  partyA: "",
  partyCContact: "",
  contractFiles: [],
});

// 计算总费用
const calculateTotalFee = computed(() => {
  const total =
    allocationForm.deposit +
    allocationForm.careFee +
    allocationForm.bedFee +
    allocationForm.otherFee -
    allocationForm.medicalInsurancePayment -
    allocationForm.governmentSubsidy;
  return Math.max(0, total).toFixed(2);
});

// 表单验证规则
const formRules = reactive({
  name: [{ required: true, message: "请输入老人姓名", trigger: "blur" }],
  idCard: [
    { required: true, message: "请输入老人身份证号", trigger: "blur" },
    {
      pattern: /^\d{17}[\dXx]$/,
      message: "身份证号格式不正确",
      trigger: "blur",
    },
  ],
  gender: [{ required: true, message: "请选择性别", trigger: "change" }],
  birthDate: [{ required: true, message: "请选择出生日期", trigger: "change" }],
  contact: [
    { required: true, message: "请输入联系方式", trigger: "blur" },
    { pattern: /^1[3-9]\d{9}$/, message: "手机号格式不正确", trigger: "blur" },
  ],
  address: [{ required: true, message: "请输入家庭住址", trigger: "blur" }],
});

// 选项数据
const ethnicityOptions = [
  { label: "汉族", value: "1" },
  { label: "蒙古族", value: "2" },
  { label: "回族", value: "3" },
  { label: "藏族", value: "4" },
  { label: "维吾尔族", value: "5" },
];

const politicalStatusOptions = [
  { label: "群众", value: "1" },
  { label: "中共党员", value: "2" },
  { label: "共青团员", value: "3" },
  { label: "民主党派", value: "4" },
];

const hobbies = [
  { label: "唱", value: "1" },
  { label: "跳", value: "2" },
  { label: "rapper", value: "3" },
  { label: "篮球", value: "4" },
];

const religionOptions = [
  { label: "无", value: "1" },
  { label: "佛教", value: "2" },
  { label: "道教", value: "3" },
  { label: "基督教", value: "4" },
  { label: "天主教", value: "5" },
  { label: "伊斯兰教", value: "6" },
];

const maritalStatusOptions = [
  { label: "未婚", value: "1" },
  { label: "已婚", value: "2" },
  { label: "离异", value: "3" },
  { label: "丧偶", value: "4" },
];

const educationOptions = [
  { label: "小学", value: "1" },
  { label: "初中", value: "2" },
  { label: "高中", value: "3" },
  { label: "大专", value: "4" },
  { label: "本科", value: "5" },
  { label: "硕士及以上", value: "6" },
];

const incomeSourceOptions = [
  { label: "退休金", value: "1" },
  { label: "子女供养", value: "2" },
  { label: "个人储蓄", value: "3" },
  { label: "政府补贴", value: "4" },
  { label: "其他", value: "5" },
];

const medicalInsuranceOptions = [
  { label: "城镇职工医保", value: "1" },
  { label: "城乡居民医保", value: "2" },
  { label: "新农合", value: "3" },
  { label: "商业保险", value: "4" },
  { label: "自费", value: "5" },
];

const relationshipOptions = [
  { label: "子女", value: "1" },
  { label: "配偶", value: "2" },
  { label: "兄弟姐妹", value: "3" },
  { label: "亲属", value: "4" },
  { label: "朋友", value: "5" },
];

const diseaseOptions = [
  { label: "无疾病", value: "无疾病" },
  { label: "冠心病I25.1", value: "冠心病I25.1" },
  { label: "糖尿病E10-E14", value: "糖尿病E10-E14" },
  { label: "肺炎J14", value: "肺炎J14" },
  { label: "高血压L10", value: "高血压L10" },
  { label: "癫痫G40", value: "癫痫G40" },
  { label: "艾滋病B24", value: "艾滋病B24" },
  { label: "慢性肾功能衰竭N18-N19", value: "慢性肾功能衰竭N18-N19" },
  { label: "脑出血l60-l62", value: "脑出血l60-l62" },
  { label: "脑梗塞l63", value: "脑梗塞l63" },
  { label: "尿路感染", value: "尿路感染" },
  { label: "帕金森综合征G20-G22", value: "帕金森综合征G20-G22" },
  { label: "消化道出血K20-K31", value: "消化道出血K20-K31" },
  { label: "肿瘤C00-C48", value: "肿瘤C00-C48" },
  { label: "截肢（6个月内）", value: "截肢（6个月内）" },
  { label: "骨折（3个月内）", value: "骨折（3个月内）" },
];

const riskEvents = [
  { label: "跌倒", key: "fall" },
  { label: "走失", key: "wandering" },
  { label: "噎食", key: "choking" },
  { label: "自杀", key: "suicide" },
  { label: "昏迷", key: "coma" },
];

const riskOptions = [
  { label: "无", value: "无" },
  { label: "发生过1次", value: "发生过1次" },
  { label: "发生过2次", value: "发生过2次" },
  { label: "发生过3次以上", value: "发生过3次以上" },
];

const woundOptions = [
  { label: "无", value: "无" },
  { label: "擦伤", value: "擦伤" },
  { label: "烧烫伤", value: "烧烫伤" },
  { label: "术后伤口", value: "术后伤口" },
  { label: "糖尿病足溃疡", value: "糖尿病足溃疡" },
  { label: "血管性溃疡", value: "血管性溃疡" },
  { label: "其他伤口", value: "其他伤口" },
];

const specialCareOptions = [
  { label: "无", value: "无" },
  { label: "胃管", value: "胃管" },
  { label: "尿管", value: "尿管" },
  { label: "气管切开", value: "气管切开" },
  { label: "无创呼吸机", value: "无创呼吸机" },
  { label: "透析", value: "透析" },
  { label: "胃/肠/膀胱造痿", value: "胃/肠/膀胱造痿" },
  { label: "其他", value: "其他" },
];

const selfCareOptions = [
  { label: "不能自理", value: "不能自理" },
  { label: "轻度依赖", value: "轻度依赖" },
  { label: "中度依赖", value: "中度依赖" },
  { label: "可自理", value: "可自理" },
];

const dementiaSignOptions = [
  { label: "行为异常", value: "行为异常" },
  { label: "记忆障碍", value: "记忆障碍" },
  { label: "日常生活能力减退", value: "日常生活能力减退" },
  { label: "呆坐", value: "呆坐" },
];

// 分数映射表
const scoreMapping = {
  // 自理能力得分映射
  selfCareAbility: {
    A: 4, // 完全自理
    B: 3, // 基本自理
    C: 2, // 部分自理
    D: 1, // 不能自理
    E: 0, // 无法评估
  },
  // 精神状态得分映射
  mentalStatus: {
    A: 4, // 认知功能正常
    B: 3, // 轻度认知障碍
    C: 2, // 中度认知障碍
    D: 1, // 重度认知障碍
    E: 0, // 无法评估
  },
  // 感知觉与社会参与得分映射
  perceptionSocialParticipation: {
    A: 4, // 社交活跃，情绪稳定
    B: 3, // 社交一般，偶有情绪波动
    C: 2, // 社交较少，情绪不稳定
    D: 1, // 社交困难，情绪问题明显
    E: 0, // 无法评估
  },
};

// 等级判定标准
const levelCriteria = {
  能力完好: { min: 10, max: 12 },
  轻度失能: { min: 7, max: 9 },
  中度失能: { min: 4, max: 6 },
  重度失能: { min: 0, max: 3 },
};

// 计算属性
const hasUploadedFiles = computed(() => {
  return (
    applicationForm.photo ||
    applicationForm.idCardFront ||
    applicationForm.idCardBack
  );
});

// 图片预览
const imagePreviewVisible = ref(false);
const previewImageUrl = ref("");

// 计算分数和等级
const calculateScores = () => {
  // 计算各项分数
  assessmentScores.selfCareScore =
    scoreMapping.selfCareAbility[abilityAssessment.selfCareAbility] || 0;
  assessmentScores.mentalStatusScore =
    scoreMapping.mentalStatus[abilityAssessment.mentalStatus] || 0;
  assessmentScores.perceptionScore =
    scoreMapping.perceptionSocialParticipation[
      abilityAssessment.perceptionSocialParticipation
    ] || 0;

  // 计算总分
  assessmentScores.totalScore =
    assessmentScores.selfCareScore +
    assessmentScores.mentalStatusScore +
    assessmentScores.perceptionScore;

  // 确定初步等级
  for (const [level, criteria] of Object.entries(levelCriteria)) {
    if (
      assessmentScores.totalScore >= criteria.min &&
      assessmentScores.totalScore <= criteria.max
    ) {
      assessmentScores.preliminaryLevel = level;
      break;
    }
  }

  // 如果没有匹配的等级，设为未评估
  if (
    !assessmentScores.preliminaryLevel ||
    assessmentScores.preliminaryLevel === "未评估"
  ) {
    assessmentScores.preliminaryLevel = "未评估";
  }

  // 同步到评估报告
  updateAssessmentReport();
};

// 更新评估报告数据
const updateAssessmentReport = () => {
  assessmentReport.selfCareScore = assessmentScores.selfCareScore;
  assessmentReport.mentalStatusScore = assessmentScores.mentalStatusScore;
  assessmentReport.perceptionSocialScore = assessmentScores.perceptionScore;
  assessmentReport.estimatedTotalScore = assessmentScores.totalScore;
  assessmentReport.preliminaryAbilityLevel = assessmentScores.preliminaryLevel;
  
  // 设置默认评估日期为今天
  if (!assessmentReport.assessmentDate) {
    const today = new Date();
    assessmentReport.assessmentDate = today.toISOString().split('T')[0];
  }
};

// 初始化评估报告数据
const initAssessmentReport = () => {
  const today = new Date();
  assessmentReport.assessmentDate = today.toISOString().split('T')[0];
  assessmentReport.assessor = "评估员"; // 可以设置为当前登录用户
  updateAssessmentReport();
};

// 其他变更依据复选框变化处理
const handleOtherBasisChange = (checked) => {
  if (!checked) {
    assessmentReport.otherBasis = "";
  }
};

// 监听出生日期变化，自动计算年龄
watch(
  () => applicationForm.birthDate,
  (newVal) => {
    if (newVal) {
      const birthYear = new Date(newVal).getFullYear();
      const currentYear = new Date().getFullYear();
      applicationForm.age = currentYear - birthYear;
    }
  }
);

// 监听能力评估变化，自动计算分数
watch(
  () => [
    abilityAssessment.selfCareAbility,
    abilityAssessment.mentalStatus,
    abilityAssessment.perceptionSocialParticipation,
  ],
  () => {
    calculateScores();
  },
  { deep: true }
);

// 在组件挂载时初始化
onMounted(() => {
  initAssessmentReport();
});

// 疾病诊断互斥逻辑
const handleDiseaseChange = (selectedDiseases) => {
  const noDiseaseIndex = selectedDiseases.indexOf("无疾病");
  const hasOtherDiseases = selectedDiseases.some(
    (disease) => disease !== "无疾病"
  );

  if (noDiseaseIndex > -1 && hasOtherDiseases) {
    // 如果选择了"无疾病"和其他疾病，移除"无疾病"
    healthAssessment.diseasesDiagnosis = selectedDiseases.filter(
      (disease) => disease !== "无疾病"
    );
  } else if (noDiseaseIndex > -1 && selectedDiseases.length > 1) {
    // 如果选择了"无疾病"且还有其他选项，只保留"无疾病"
    healthAssessment.diseasesDiagnosis = ["无疾病"];
  }
};

const getDiseaseDisabled = (diseaseValue) => {
  const hasNoDisease = healthAssessment.diseasesDiagnosis.includes("无疾病");
  const hasOtherDiseases = healthAssessment.diseasesDiagnosis.some(
    (disease) => disease !== "无疾病"
  );

  if (diseaseValue === "无疾病") {
    return hasOtherDiseases;
  } else {
    return hasNoDisease;
  }
};

// 伤口情况互斥逻辑
const handleWoundChange = (selectedWounds) => {
  const noWoundIndex = selectedWounds.indexOf("无");
  const hasOtherWounds = selectedWounds.some((wound) => wound !== "无");

  if (noWoundIndex > -1 && hasOtherWounds) {
    healthAssessment.woundCondition = selectedWounds.filter(
      (wound) => wound !== "无"
    );
  } else if (noWoundIndex > -1 && selectedWounds.length > 1) {
    healthAssessment.woundCondition = ["无"];
  }
};

const getWoundDisabled = (woundValue) => {
  const hasNoWound = healthAssessment.woundCondition.includes("无");
  const hasOtherWounds = healthAssessment.woundCondition.some(
    (wound) => wound !== "无"
  );

  if (woundValue === "无") {
    return hasOtherWounds;
  } else {
    return hasNoWound;
  }
};

// 特殊医疗照护情况互斥逻辑
const handleSpecialCareChange = (selectedCares) => {
  const noCareIndex = selectedCares.indexOf("无");
  const hasOtherCares = selectedCares.some((care) => care !== "无");

  if (noCareIndex > -1 && hasOtherCares) {
    healthAssessment.specialMedicalCare = selectedCares.filter(
      (care) => care !== "无"
    );
  } else if (noCareIndex > -1 && selectedCares.length > 1) {
    healthAssessment.specialMedicalCare = ["无"];
  }
};

const getSpecialCareDisabled = (careValue) => {
  const hasNoCare = healthAssessment.specialMedicalCare.includes("无");
  const hasOtherCares = healthAssessment.specialMedicalCare.some(
    (care) => care !== "无"
  );

  if (careValue === "无") {
    return hasOtherCares;
  } else {
    return hasNoCare;
  }
};

// 获取等级标签类型
const getLevelType = (level) => {
  const levelTypes = {
    能力完好: "success",
    轻度失能: "info",
    中度失能: "warning",
    重度失能: "danger",
    未评估: "info",
  };
  return levelTypes[level] || "info";
};

const getCareLevelType = (level) => {
  const levelTypes = {
    特级护理: "danger",
    一级护理: "warning",
    二级护理: "info",
    三级护理: "success",
  };
  return levelTypes[level] || "info";
};

// 方法
const addFamilyMember = () => {
  familyMembers.value.push({ name: "", contact: "", relationship: "" });
};

const removeFamilyMember = (index) => {
  if (familyMembers.value.length > 1) {
    familyMembers.value.splice(index, 1);
  } else {
    ElMessage.warning("至少需要保留一位家属信息");
  }
};

const addMedication = () => {
  healthAssessment.medicationInfo.push({
    name: "",
    method: "",
    dosage: "",
    frequency: "",
  });
};

const removeMedication = (index) => {
  if (healthAssessment.medicationInfo.length > 1) {
    healthAssessment.medicationInfo.splice(index, 1);
  } else {
    ElMessage.warning("至少需要保留一种药物");
  }
};

// 文件上传处理
const beforeAvatarUpload = (file) => {
  const isJPGOrPNG = file.type === "image/jpeg" || file.type === "image/png";
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isJPGOrPNG) {
    ElMessage.error("上传头像图片只能是 JPG/PNG 格式!");
    return false;
  }
  if (!isLt2M) {
    ElMessage.error("上传头像图片大小不能超过 2MB!");
    return false;
  }
  return true;
};

const beforeIdCardUpload = (file) => {
  const isJPGOrPNG = file.type === "image/jpeg" || file.type === "image/png";
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isJPGOrPNG) {
    ElMessage.error("上传身份证图片只能是 JPG/PNG 格式!");
    return false;
  }
  if (!isLt2M) {
    ElMessage.error("上传身份证图片大小不能超过 2MB!");
    return false;
  }
  return true;
};

const handleAvatarUpload = (options) => {
  const file = options.file;
  const reader = new FileReader();
  reader.readAsDataURL(file);
  reader.onload = () => {
    applicationForm.photo = reader.result;
    ElMessage.success("一寸照片上传成功");
  };
};

const handleIdCardFrontUpload = (options) => {
  const file = options.file;
  const reader = new FileReader();
  reader.readAsDataURL(file);
  reader.onload = () => {
    applicationForm.idCardFront = reader.result;
    ElMessage.success("身份证人像面上传成功");
  };
};

const handleIdCardBackUpload = (options) => {
  const file = options.file;
  const reader = new FileReader();
  reader.readAsDataURL(file);
  reader.onload = () => {
    applicationForm.idCardBack = reader.result;
    ElMessage.success("身份证国徽面上传成功");
  };
};

const beforeMedicalReportUpload = (file) => {
  const isPDF = file.type === "application/pdf";
  const isLt50M = file.size / 1024 / 1024 < 50;

  if (!isPDF) {
    ElMessage.error("上传文件只能是 PDF 格式!");
    return false;
  }
  if (!isLt50M) {
    ElMessage.error("上传文件大小不能超过 50MB!");
    return false;
  }
  return true;
};

const handleMedicalReportUpload = (options) => {
  const file = options.file;
  healthAssessment.medicalReport = [file];
  ElMessage.success("体检报告上传成功");
};

const previewImage = (url) => {
  previewImageUrl.value = url;
  imagePreviewVisible.value = true;
};

// 床位选择相关方法
const openBedSelectionDialog = () => {
  bedSelectionDialogVisible.value = true;
  selectedBedId.value = null;
};

const selectBed = (bed) => {
  if (bed.status === "空闲") {
    selectedBedId.value = bed.id;
  } else {
    ElMessage.warning("该床位已被预定，请选择其他床位");
  }
};

const confirmBedSelection = () => {
  if (selectedBedId.value) {
    const selectedBed = availableBeds.value.find(
      (bed) => bed.id === selectedBedId.value
    );
    if (selectedBed) {
      allocationForm.selectedBed = `${selectedBed.number} (${selectedBed.room} ${selectedBed.type})`;
      allocationForm.bedFee = selectedBed.price;
      bedSelectionDialogVisible.value = false;
      ElMessage.success(`已选择床位：${selectedBed.number}`);
    }
  } else {
    ElMessage.warning("请选择一个床位");
  }
};

// 审批相关方法
const approveApplication = () => {
  ElMessageBox.confirm("确定批准此入住申请吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    mainSteps.value[2].completed = true;
    nextMainStep();
    ElMessage.success("申请已批准");
  });
};

const rejectApplication = () => {
  ElMessageBox.confirm("确定拒绝此入住申请吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    ElMessage.error("申请已拒绝");
  });
};

const previewContract = () => {
  ElMessage.info("合同预览功能开发中");
};

const completeContract = () => {
  ElMessageBox.confirm("确定完成签约吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    mainSteps.value[4].completed = true;
    ElMessage.success("签约已完成");
  });
};

// 导航方法
const nextMainStep = () => {
  if (currentMainStep.value < mainSteps.value.length - 1) {
    mainSteps.value[currentMainStep.value].completed = true;
    currentMainStep.value++;
  }
};

const prevMainStep = () => {
  if (currentMainStep.value > 0) {
    currentMainStep.value--;
  }
};

const goToMainStep = (index) => {
  if (index <= currentMainStep.value) {
    currentMainStep.value = index;
  }
};

// 申请入住子流程导航
const nextApplicationSubStep = async () => {
  // 验证当前步骤表单
  if (currentApplicationSubStep.value === 0) {
    // 验证基本信息
    const basicInfoForm = document.querySelector(".basic-info-form");
    if (basicInfoForm) {
      try {
        await basicInfoForm.validate();
      } catch (error) {
        ElMessage.error("请完善基本信息");
        return;
      }
    }
  } else if (currentApplicationSubStep.value === 1) {
    // 验证家属信息
    const hasValidFamilyMember = familyMembers.value.some(
      (member) => member.name && member.contact && member.relationship
    );
    if (!hasValidFamilyMember) {
      ElMessage.error("请至少完善一位家属信息");
      return;
    }
  }

  if (currentApplicationSubStep.value < applicationSubSteps.value.length - 1) {
    applicationSubSteps.value[currentApplicationSubStep.value].completed = true;
    currentApplicationSubStep.value++;
  }
};

const prevApplicationSubStep = () => {
  if (currentApplicationSubStep.value > 0) {
    currentApplicationSubStep.value--;
  }
};

const goToApplicationSubStep = (index) => {
  if (index <= currentApplicationSubStep.value) {
    currentApplicationSubStep.value = index;
  }
};

// 入住评估子流程导航
const nextAssessmentSubStep = () => {
  if (currentAssessmentSubStep.value < assessmentSubSteps.value.length - 1) {
    assessmentSubSteps.value[currentAssessmentSubStep.value].completed = true;
    currentAssessmentSubStep.value++;
  }
};

const prevAssessmentSubStep = () => {
  if (currentAssessmentSubStep.value > 0) {
    currentAssessmentSubStep.value--;
  }
};

const goToAssessmentSubStep = (index) => {
  if (index <= currentAssessmentSubStep.value) {
    currentAssessmentSubStep.value = index;
  }
};

const completeApplicationStep = async () => {
  // 验证资料上传
  if (
    !applicationForm.photo ||
    !applicationForm.idCardFront ||
    !applicationForm.idCardBack
  ) {
    ElMessage.error("请上传所有必需的资料照片");
    return;
  }

  await ElMessageBox.confirm("确定完成申请入住信息吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  });
  currentApplicationSubStep.value = 0;
  applicationSubSteps.value[currentApplicationSubStep.value].completed = true;
  mainSteps.value[0].completed = true;
  currentMainStep.value = 1;
  console.log(applicationForm);
  
  console.log("申请入住成功");
  ElMessage.success("申请入住信息提交成功！");
};

const completeAssessmentStep = async () => {
  // 验证评估数据
  if (!assessmentReport.assessor || !assessmentReport.assessmentDate) {
    ElMessage.error("请填写评估人员信息和评估日期");
    return;
  }

  await ElMessageBox.confirm("确定完成入住评估吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  });

  assessmentSubSteps.value[currentAssessmentSubStep.value].completed = true;
  mainSteps.value[1].completed = true;
  currentMainStep.value = 2;
  currentAssessmentSubStep.value = 0;
  console.log(abilityAssessment);
  console.log(healthAssessment);
  console.log(assessmentReport);
  
  ElMessage.success("入住评估完成！");
};

const submitting = ref(false);

const submitCompleteApplication = async () => {
  if (submitting.value) return;
  
  try {
    submitting.value = true;
    
    const completeData = createCompleteApplicationData();
    
    console.log('完整提交数据:', completeData);
    
    const validationErrors = validateCompleteData(completeData);
    if (validationErrors.length > 0) {
      ElMessage.error(`数据验证失败：${validationErrors.join('，')}`);
      return;
    }
    
    const confirmResult = await ElMessageBox.confirm(
      '确定提交整个申请吗？提交后将进入审批流程。',
      '确认提交',
      {
        confirmButtonText: '确定提交',
        cancelButtonText: '再检查一下',
        type: 'warning'
      }
    );
    
    if (confirmResult === 'confirm') {
      const loadingInstance = ElLoading.service({
        lock: true,
        text: '正在提交申请，请稍候...',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      
      try {
        // 发送请求
        const response = await fetch('/data/Inmanagement/submitApplication', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify(completeData)
        });
        
        // 检查响应状态
        if (!response.ok) {
         throw new Error(`HTTP ${response.status}: ${response.statusText}`);
        }

        // 检查响应内容类型
        const contentType = response.headers.get('content-type');
        if (!contentType || !contentType.includes('application/json')) {
          const text = await response.text();
          console.error('后端返回非JSON数据:', text.substring(0, 200));
          throw new Error('服务器返回了非JSON格式的响应');
        }
        
        // 解析JSON
        const result = await response.json();
        
        if (result.success) {
          ElMessage.success('申请提交成功！');
          mainSteps.value.forEach(step => {
            step.completed = true;
          });
          console.log('申请提交成功，ID:', result.data);
        } else {
          ElMessage.error(`提交失败：${result.message || '未知错误'}`);
        }
      } catch (error) {
        console.error('提交申请失败:', error);
        
        // 更详细的错误信息
        if (error.message.includes('Failed to fetch')) {
          ElMessage.error('提交失败：网络连接错误，请检查网络连接');
        } else if (error.message.includes('HTTP')) {
          ElMessage.error(`提交失败：服务器错误 (${error.message})`);
        } else if (error.message.includes('JSON')) {
          ElMessage.error('提交失败：服务器返回数据格式错误');
        } else {
          ElMessage.error(`提交失败：${error.message}`);
        }
      } finally {
        loadingInstance.close();
      }
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('提交过程异常:', error);
    }
  } finally {
    submitting.value = false;
  }
};

// 创建完整的数据封装对象
const createCompleteApplicationData = () => {
  return {
    // 申请基本信息
    elderly: {
      ...applicationForm,
      age: parseInt(applicationForm.age) || 0,
    },

    // 家属信息
    familyMembers: familyMembers.value.map((member) => ({
      name: member.name?.trim() || "",
      contact: member.contact?.trim() || "",
      relationship: member.relationship || "",
    })),

    // 健康评估数据
    healthAssessment: {
      diseasesDiagnosis: [...healthAssessment.diseasesDiagnosis],
      medicationInfo: healthAssessment.medicationInfo.map((med) => ({
        name: med.name?.trim() || "",
        method: med.method?.trim() || "",
        dosage: med.dosage?.trim() || "",
        frequency: med.frequency?.trim() || "",
      })),
      riskFactors: { ...healthAssessment.riskFactors },
      woundCondition: [...healthAssessment.woundCondition],
      specialMedicalCare: [...healthAssessment.specialMedicalCare],
      selfCareAbility: healthAssessment.selfCareAbility || "",
      dementiaPrecursors: [...healthAssessment.dementiaPrecursors],
      otherConditions: healthAssessment.otherConditions || "",
      medicalReport: healthAssessment.medicalReport || [],
    },

    // 能力评估数据
    abilityAssessment: {
      selfCareAbility: abilityAssessment.selfCareAbility || "",
      mentalStatus: abilityAssessment.mentalStatus || "",
      perceptionSocialParticipation:
        abilityAssessment.perceptionSocialParticipation || "",
    },

    // 评估报告数据（包含评估分数）
    assessmentReport: {
      // 评估分数
      selfCareScore: assessmentReport.selfCareScore || 0,
      mentalStatusScore: assessmentReport.mentalStatusScore || 0,
      perceptionSocialScore: assessmentReport.perceptionSocialScore || 0,
      estimatedTotalScore: assessmentReport.estimatedTotalScore || 0,
      preliminaryAbilityLevel: assessmentReport.preliminaryAbilityLevel || "",

      // 等级变更依据
      levelChangeBasis: [...assessmentReport.levelChangeBasis],
      otherBasis: assessmentReport.otherBasis || "",

      // 最终等级和评估信息
      finalAbilityLevel: assessmentReport.finalAbilityLevel || "",
      assessmentDate: assessmentReport.assessmentDate || "",
      assessor: assessmentReport.assessor || "",

      // 其他评估信息
      overallScore: assessmentReport.overallScore || 0,
      careLevel: assessmentReport.careLevel || "",
      remarks: assessmentReport.remarks || "",
    },

    // 入住配置数据
    checkInManagement: {
      stayPeriod: allocationForm.stayPeriod || [],
      careLevel: allocationForm.careLevel || "",
      selectedBed: allocationForm.selectedBed || "",
      feePeriod: allocationForm.feePeriod || [],
      deposit: parseFloat(allocationForm.deposit) || 0,
      careFee: parseFloat(allocationForm.careFee) || 0,
      bedFee: parseFloat(allocationForm.bedFee) || 0,
      otherFee: parseFloat(allocationForm.otherFee) || 0,
      medicalInsurancePayment:
        parseFloat(allocationForm.medicalInsurancePayment) || 0,
      governmentSubsidy: parseFloat(allocationForm.governmentSubsidy) || 0,
    },

    // 签约数据
    contract: {
      contractNumber: contractForm.contractNumber || "",
      contractName: contractForm.contractName || "",
      contractPeriod: contractForm.contractPeriod || [],
      signDate: contractForm.signDate || "",
      partyA: contractForm.partyA || "",
      partyCContact: contractForm.partyCContact || "",
      contractFiles: contractForm.contractFiles || [],
    },

    // 元数据
    metadata: {
      submittedAt: new Date().toISOString(),
      currentStep: currentMainStep.value,
    },
  };
};

// 数据验证
const validateCompleteData = (data) => {
  const errors = [];

  // 验证基本信息
  if (!data.elderly.name?.trim()) {
    errors.push("老人姓名为必填项");
  }

  if (
    !data.elderly.idCard ||
    !/^\d{17}[\dXx]$/.test(data.elderly.idCard)
  ) {
    errors.push("身份证号格式不正确");
  }

  if (
    !data.elderly.contact ||
    !/^1[3-9]\d{9}$/.test(data.elderly.contact)
  ) {
    errors.push("联系方式格式不正确");
  }

  // 验证家属信息
  if (data.familyMembers.length === 0) {
    errors.push("至少需要填写一位家属信息");
  }

  // 验证入住配置
  if (!data.checkInManagement.selectedBed) {
    errors.push("请选择入住床位");
  }

  if (!data.checkInManagement.careLevel) {
    errors.push("请选择护理等级");
  }

  return errors;
};
</script>

<style scoped>
.senior-care-app {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
  color: #333;
  font-family: "Helvetica Neue", Helvetica, "PingFang SC", "Hiragino Sans GB",
    Arial, sans-serif;
}

.header {
  background-color: #409eff;
  color: white;
  padding: 15px 20px;
  border-radius: 8px 8px 0 0;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  text-align: center;
}

.process-steps {
  display: flex;
  justify-content: space-between;
  margin: 30px 0;
  position: relative;
}

.process-steps::before {
  content: "";
  position: absolute;
  top: 20px;
  left: 0;
  right: 0;
  height: 2px;
  background-color: #e4e7ed;
  z-index: 1;
}

.step {
  display: flex;
  flex-direction: column;
  align-items: center;
  position: relative;
  z-index: 2;
  flex: 1;
  cursor: pointer;
}

.step-circle {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background-color: #e4e7ed;
  color: #909399;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  margin-bottom: 10px;
  border: 2px solid #e4e7ed;
  transition: all 0.3s;
}

.step.active .step-circle {
  background-color: #409eff;
  color: white;
  border-color: #409eff;
}

.step.completed .step-circle {
  background-color: #67c23a;
  color: white;
  border-color: #67c23a;
}

.step-title {
  font-size: 14px;
  color: #606266;
  text-align: center;
  font-weight: 500;
}

.step.active .step-title {
  color: #409eff;
  font-weight: bold;
}

/* 子流程步骤样式 */
.sub-process-steps {
  display: flex;
  justify-content: center;
  margin: 20px 0;
  gap: 40px;
}

.sub-step {
  display: flex;
  flex-direction: column;
  align-items: center;
  cursor: pointer;
}

.sub-step-circle {
  width: 30px;
  height: 30px;
  border-radius: 50%;
  background-color: #e4e7ed;
  color: #909399;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  margin-bottom: 8px;
  border: 2px solid #e4e7ed;
  transition: all 0.3s;
  font-size: 12px;
}

.sub-step.active .sub-step-circle {
  background-color: #409eff;
  color: white;
  border-color: #409eff;
}

.sub-step.completed .sub-step-circle {
  background-color: #67c23a;
  color: white;
  border-color: #67c23a;
}

.sub-step-title {
  font-size: 12px;
  color: #606266;
  font-weight: 500;
}

.sub-step.active .sub-step-title {
  color: #409eff;
  font-weight: bold;
}

.step-content {
  background: white;
  padding: 30px;
  border-radius: 8px;
  box-shadow: 0 2px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.step-content h2 {
  margin-bottom: 20px;
  color: #303133;
  border-bottom: 1px solid #e4e7ed;
  padding-bottom: 10px;
  font-size: 20px;
  font-weight: 600;
}

.action-buttons {
  text-align: center;
  margin-top: 20px;
}

/* 家属信息表格样式 */
.family-member-table {
  margin-top: 20px;
}

.add-button-container {
  margin: 15px 0;
  text-align: left;
}

.family-tips {
  margin-top: 15px;
}

/* 资料上传样式 */
.upload-section {
  display: flex;
  flex-wrap: wrap;
  gap: 30px;
  margin-top: 20px;
}

.upload-item {
  flex: 1;
  min-width: 250px;
}

.upload-label {
  font-weight: bold;
  margin-bottom: 10px;
  color: #606266;
}

.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: all 0.3s;
  width: 100%;
  height: 180px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.avatar-uploader:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
}

.avatar {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.upload-tips {
  font-size: 12px;
  color: #909399;
  margin-top: 8px;
}

.upload-preview {
  margin-top: 30px;
  padding: 20px;
  background-color: #f8f9fa;
  border-radius: 6px;
}

.upload-preview h3 {
  margin-bottom: 15px;
  color: #303133;
}

.preview-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.preview-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 12px;
  background: white;
  border-radius: 4px;
  border: 1px solid #e4e7ed;
}

/* 评估相关样式 */
.assessment-section {
  margin-bottom: 30px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
  border-left: 4px solid #409eff;
}

.assessment-section h3 {
  margin-bottom: 15px;
  color: #409eff;
  border-bottom: 1px solid #e4e7ed;
  padding-bottom: 8px;
  font-size: 16px;
  font-weight: 600;
}

.health-subsection {
  margin-bottom: 20px;
}

.health-subsection h4 {
  margin-bottom: 10px;
  color: #606266;
  font-size: 14px;
  font-weight: 600;
}

.checkbox-group {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
}

.risk-events {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.risk-event-item {
  display: flex;
  align-items: center;
  gap: 15px;
}

.event-label {
  min-width: 80px;
  font-weight: bold;
}

.ability-assessment {
  display: flex;
  flex-direction: column;
  gap: 25px;
}

.assessment-question {
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
  border-left: 4px solid #409eff;
}

.assessment-question h3 {
  margin-bottom: 10px;
  color: #303133;
  font-size: 16px;
  font-weight: 600;
}

.assessment-question p {
  margin-bottom: 15px;
  color: #606266;
}

/* 实时分数显示样式 */
.score-preview {
  margin-top: 30px;
}

.score-display {
  display: flex;
  flex-direction: column;
  gap: 12px;
  padding: 20px;
}

.score-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
  border-bottom: 1px solid #e4e7ed;
}

.score-item:last-child {
  border-bottom: none;
}

.score-item.total {
  border-top: 2px solid #409eff;
  padding-top: 15px;
  margin-top: 10px;
}

.score-item.level {
  background: #f0f9ff;
  padding: 12px;
  border-radius: 6px;
  margin-top: 10px;
}

/* 评估报告特定样式 */
.assessment-report {
  display: flex;
  flex-direction: column;
  gap: 25px;
}

.report-section {
  margin-bottom: 30px;
}

.main-title {
  color: #409eff;
  border-bottom: 2px solid #409eff;
  padding-bottom: 10px;
  margin-bottom: 20px;
  font-size: 20px;
  font-weight: 600;
}

.subsection {
  margin-bottom: 25px;
}

.subsection h4 {
  color: #606266;
  margin-bottom: 15px;
  font-size: 16px;
  font-weight: 600;
}

.score-card,
.total-score-card {
  background: #f8f9fa;
}

.score-details {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.score-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
  border-bottom: 1px solid #e4e7ed;
}

.score-row:last-child {
  border-bottom: none;
}

.score-label {
  color: #606266;
  font-weight: 500;
}

.score-value {
  color: #409eff;
  font-weight: bold;
  font-size: 16px;
}

.total-score {
  text-align: center;
  padding: 20px;
}

.total-label {
  font-size: 18px;
  color: #606266;
  margin-right: 10px;
}

.total-value {
  font-size: 24px;
  color: #67c23a;
  font-weight: bold;
}

.preliminary-level {
  text-align: center;
  padding: 20px;
}

.final-level {
  padding: 15px;
}

.level-options {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.change-reasons {
  padding: 15px;
}

.reason-checkboxes {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.other-reason-input {
  margin-top: 15px;
  padding-top: 15px;
  border-top: 1px solid #e4e7ed;
}

.report-summary {
  padding: 20px;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.summary-item {
  display: flex;
  align-items: flex-start;
  gap: 10px;
}

.summary-item strong {
  min-width: 100px;
  color: #303133;
}

.text-muted {
  color: #909399;
  font-style: italic;
}

/* 入住配置特定样式 */
.allocation-section {
  margin-bottom: 30px;
}

.allocation-section:last-child {
  margin-bottom: 0;
}

.date-range-picker,
.care-level-select,
.bed-selection,
.fee-period,
.fee-details {
  padding: 15px;
}

.selected-bed-info {
  margin-top: 10px;
  padding: 10px;
  background-color: #f0f9ff;
  border-radius: 4px;
  border: 1px solid #409eff;
}

.bed-info-text {
  color: #409eff;
  font-weight: 500;
}

.fee-unit {
  margin-left: 10px;
  color: #606266;
}

.total-fee {
  border-top: 2px solid #409eff;
  padding-top: 15px;
  margin-top: 15px;
}

.total-amount {
  font-size: 18px;
  color: #67c23a;
  font-weight: bold;
}

/* 床位选择对话框样式 */
.bed-selection-dialog {
  max-height: 400px;
  overflow-y: auto;
}

.bed-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 15px;
  margin-bottom: 20px;
}

.bed-item {
  border: 2px solid #e4e7ed;
  border-radius: 8px;
  padding: 15px;
  cursor: pointer;
  transition: all 0.3s;
}

.bed-item:hover {
  border-color: #409eff;
  background-color: #f0f9ff;
}

.bed-item.selected {
  border-color: #409eff;
  background-color: #ecf5ff;
}

.bed-info {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.bed-number {
  font-size: 16px;
  font-weight: bold;
  color: #409eff;
}

.bed-details {
  font-size: 14px;
  color: #606266;
}

.bed-price {
  color: #67c23a;
  font-weight: 500;
}

.dialog-actions {
  text-align: right;
  padding-top: 20px;
  border-top: 1px solid #e4e7ed;
}

/* 审批流程样式 */
.approval-process {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.process-item {
  display: flex;
  align-items: center;
  gap: 15px;
  padding: 15px;
  border-radius: 8px;
  background-color: #f5f7fa;
}

.process-item.completed {
  border-left: 4px solid #67c23a;
}

.process-item.active {
  border-left: 4px solid #409eff;
}

.process-item.pending {
  border-left: 4px solid #e6a23c;
}

.process-icon {
  width: 30px;
  height: 30px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  color: white;
}

.process-item.completed .process-icon {
  background-color: #67c23a;
}

.process-item.active .process-icon {
  background-color: #409eff;
}

.process-item.pending .process-icon {
  background-color: #e6a23c;
}

.process-info {
  flex: 1;
}

.process-title {
  font-weight: bold;
  margin-bottom: 5px;
  color: #303133;
}

.process-time {
  font-size: 12px;
  color: #909399;
}

.process-status {
  font-size: 12px;
  color: #67c23a;
}

.approval-card {
  margin-bottom: 20px;
}

:deep(.el-form-item__label) {
  font-weight: bold;
  color: #333;
}

:deep(.el-radio) {
  margin-right: 15px;
  margin-bottom: 8px;
}

:deep(.el-checkbox) {
  margin-right: 15px;
  margin-bottom: 8px;
}

:deep(.el-input__inner) {
  color: #333;
}

:deep(.el-textarea__inner) {
  color: #333;
}

:deep(.el-select .el-input__inner) {
  color: #333;
}

:deep(.el-table) {
  color: #333;
}

:deep(.el-table th) {
  color: #333;
  font-weight: bold;
}

:deep(.el-alert__title) {
  color: #333;
}

:deep(.el-alert__description) {
  color: #666;
}
</style>